import http from '@ohos.net.http'

class CloudProcess{
  //华为云项目ID
  private project_id:string='ffdf415260fe4bd6ae113242aadfc0c9'
  //华为云设备ID
  private device_id:string='66105f4771d845632a0403e7_E53_IA'
  //华为云账号AK
  private AK:string= 'DHDLRVMFOIJXKEOZVWNE'
  //华为云账号SK
  private SK:string= '3Z1nxKe4eesAVvAipk6ThlkL7MUmaYds8ZsrMPy7'
  //华为云账号Token
  private Token:string=null
  //是否成功获取到华为云账号Token
  private HavaToken=false
  //华为云设备列表
  public remote_device_status: Array<{
    temperator: string,
    humidity: string,
    luminance: string,
    is_rain: string,
    is_smoke: string,
    is_fire: string,
    is_body:string,
    is_doorbell:string
  }>

  /***************************************************************
   * 函数名称: CloudInit
   * 说    明: 初始化数组
   * 参    数: 无
   * 返 回 值: 无
   ***************************************************************/
  CloudInit(){
    this.remote_device_status = [];
  }

  /***************************************************************
   * 函数名称: getAccessToken
   * 说    明: 获取Token
   * 参    数: 无
   * 返 回 值: 无
   ***************************************************************/
  getAccessToken(){
    let httpRequest = http.createHttp();
    httpRequest.request(
      'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens',
      {
        method:http.RequestMethod.POST,
        header:{
          'Content-Type': 'application/json'
        },
        extraData:this.GetTokenBody(),
        connectTimeout: 60000,
        readTimeout: 60000,
      },(err, data) => {
      if (!err) {
        console.log("successful")
        this.Token = data.header['x-subject-token']
        console.log("access_token:" + this.Token)
        this.HavaToken=true
      } else {
        console.log('Result1_error:' + JSON.stringify(err));
        httpRequest.destroy();
        this.HavaToken=false
      }
    })
    return this.HavaToken
  }

  /***************************************************************
   * 函数名称: GetTokenBody
   * 说    明: 获取Token的Body
   * 参    数: 无
   * 返 回 值: 无
   ***************************************************************/
  GetTokenBody() {
    return {
      "auth": {
        "identity": {
          "methods": [
            "hw_ak_sk"
          ],
          "hw_ak_sk": {
            "access": {
              "key": this.AK
            },
            "secret": {
              "key": this.SK
            }
          }
        },
        "scope": {
          "project": {
            "name": "cn-east-3"
          }
        }
      }
    }
  }

  /***************************************************************
   * 函数名称: ControlDevices
   * 说    明: 初始化数组
   * 参    数: 无
   * 返 回 值: 无
   ***************************************************************/
  async ControlDevices(DeviceCmdName:string,DeviceName:string,DeviceState:string) {
    let httpRequest = http.createHttp();
    switch (DeviceName){
      case "window":
        httpRequest.request("https://a81bf3d259.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/" + this.project_id + "/devices/" + this.device_id + "/commands", {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json',
            'X-Auth-Token': this.Token //需要在请求头中加入之前获取的token
          },
          extraData: {
            "service_id": "智慧管家",
            "command_name": DeviceCmdName.toString(),
            "paras":{"window": DeviceState}
          }
        }, (err, data) => {
          console.info("下发结果_服务器返回结果:" + data.result)
          if (err) {
            console.info('下发结果_error:' + JSON.stringify(err));
            httpRequest.destroy();
          }
        })
      break;
      case "car_door":
        httpRequest.request("https://a81bf3d259.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/" + this.project_id + "/devices/" + this.device_id + "/commands", {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json',
            'X-Auth-Token': this.Token //需要在请求头中加入之前获取的token
          },
          extraData: {
            "service_id": "智慧管家",
            "command_name": DeviceCmdName.toString(),
            "paras":{"car_door": DeviceState}
          }
        }, (err, data) => {
          console.info("下发结果_服务器返回结果:" + data.result)
          if (err) {
            console.info('下发结果_error:' + JSON.stringify(err));
            httpRequest.destroy();
          }
        })
        break;
      case "lamp":
        httpRequest.request("https://a81bf3d259.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/" + this.project_id + "/devices/" + this.device_id + "/commands", {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json',
            'X-Auth-Token': this.Token //需要在请求头中加入之前获取的token
          },
          extraData: {
            "service_id": "智慧管家",
            "command_name": DeviceCmdName.toString(),
            "paras":{"lamp": DeviceState}
          }
        }, (err, data) => {
          console.info("下发结果_服务器返回结果:" + data.result)
          if (err) {
            console.info('下发结果_error:' + JSON.stringify(err));
            httpRequest.destroy();
          }
        })
        break;
      case "door":
        httpRequest.request("https://a81bf3d259.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/" + this.project_id + "/devices/" + this.device_id + "/commands", {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json',
            'X-Auth-Token': this.Token //需要在请求头中加入之前获取的token
          },
          extraData: {
            "service_id": "智慧管家",
            "command_name": DeviceCmdName.toString(),
            "paras":{"door": DeviceState}
          }
        }, (err, data) => {
          console.info("下发结果_服务器返回结果:" + data.result)
          if (err) {
            console.info('下发结果_error:' + JSON.stringify(err));
            httpRequest.destroy();
          }
        })
        break;
      case "change":
        httpRequest.request("https://a81bf3d259.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/" + this.project_id + "/devices/" + this.device_id + "/commands", {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json',
            'X-Auth-Token': this.Token //需要在请求头中加入之前获取的token
          },
          extraData: {
            "service_id": "智慧管家",
            "command_name": DeviceCmdName.toString(),
            "paras":{"change": DeviceState}
          }
        }, (err, data) => {
          console.info("下发结果_服务器返回结果:" + data.result)
          if (err) {
            console.info('下发结果_error:' + JSON.stringify(err));
            httpRequest.destroy();
          }
        })
        break;
    }

  }

  /***************************************************************
   * 函数名称: GetSensorData
   * 说    明: 异步获取云平台数据
   * 参    数: 无
   * 返 回 值: 无
   ***************************************************************/
  async GetSensorData() {
    let httpRequest = http.createHttp();
    httpRequest.request("https://a81bf3d259.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/" + this.project_id + "/devices/" + this.device_id + "/shadow", {
      method: http.RequestMethod.GET,
      header: {
        'Content-Type': 'application/json',
        'X-Auth-Token': this.Token //需要在请求头中加入之前获取的token
      },
    }, (err, data) => {
      if (!err) {
        console.info("服务器返回结果:" + data.result)
        if (this.getAccessToken() == true) {
          let recognitionResult = JSON.parse(data.result.toString());
          console.log("ArrayLen：" + this.remote_device_status.length);
          this.remote_device_status.push({
            temperator: recognitionResult.shadow[0].reported.properties.温度,
            humidity: recognitionResult.shadow[0].reported.properties.湿度,
            luminance: recognitionResult.shadow[0].reported.properties.亮度,
            is_rain: recognitionResult.shadow[0].reported.properties.雨滴,
            is_smoke: recognitionResult.shadow[0].reported.properties.烟感,
            is_fire: recognitionResult.shadow[0].reported.properties.火焰,
            is_body: recognitionResult.shadow[0].reported.properties.人体红外,
            is_doorbell:recognitionResult.shadow[0].reported.properties.门铃
          })
        }
        else {
          console.log("ArrayLenfail：");
        }
      } else {
        console.info('Result2_error:' + JSON.stringify(err));
        httpRequest.destroy();
      }
    })
  }
}
export default new CloudProcess()